﻿/*
#------------------------------------------------------------------------------
#-- Program Name:	[dbo].[spRest_RecoverDatabase]
#-- Purpose:		Recovers a database from a restore process
#--	Last Update:	05/23/2013
#--					For a complete history - please review comments in Version
#--					Control.
#------------------------------------------------------------------------------
*/
CREATE PROCEDURE [dbo].[spRest_RecoverDatabase]
(
	@database_name			sysname,
	@as_standby				bit			= 0
)
WITH EXECUTE AS OWNER
AS

SET NOCOUNT ON

--- Declare Local Variables
DECLARE	@sCommand nvarchar(3000), @log_dir nvarchar(4000)

--- Get the default log file location (for the standby log file)
EXEC	[dbo].[spMaint_GetDefaultLogDirectory] @log_directory_name = @log_dir OUTPUT
IF RIGHT(@log_dir, 1) <> '\'
	SELECT	@log_dir = @log_dir + '\'

--- Build the command
IF @as_standby = 0
	SELECT	@sCommand = 'IF EXISTS (SELECT TOP 1 * FROM master.sys.databases WHERE name = ''' + @database_name + ''' AND state = 1)
		RESTORE DATABASE ' + QUOTENAME(@database_name) + ' WITH RECOVERY;'
ELSE
	SELECT	@sCommand = 'IF EXISTS (SELECT TOP 1 * FROM master.sys.databases WHERE name = ''' + @database_name + ''' AND state = 1)
		RESTORE LOG ' + QUOTENAME(@database_name) + ' WITH STANDBY=''' + @log_dir + @database_name + '_StandbyLog.stb'';'

--- Recover the database
EXEC	(@sCommand)

SET NOCOUNT OFF